/**
 * @file	halPeripheral.c
 * @author	chipsea
 * @brief	
 * @version	0.1
 * @date	2020-11-30
 * @copyright Copyright (c) 2020, CHIPSEA Co., Ltd.
 * @note
 */

/*********************************************************************
 * INCLUDES
 */
#include "log.h"
#include "key.h"
#include "OSAL.h"
#include "gpio.h"
#include "clock.h"
#include "error.h"
#include "pwrmgr.h"
#include "rom_sym_def.h"
#include "global_config.h"
#include "halPeripheral.h"
#include "uart.h"


#define UART_BUF_SIZE	256

uint8 Hal_TaskID;

typedef struct
{
	uint16_t wr;
	uint16_t rd;
	uint8_t  data[UART_BUF_SIZE];
} uart_data_t;
uart_data_t uart_data;
/**
 * @fn      void HalPeripheral_Init(uint8 task_id)
 * @brief   Peripheral initialization
 * @param   task_id
 * @return  none
 */
void uart_receive_callback(uart_Evt_t* pev)
{
	switch(pev->type)
	{
		case UART_EVT_TYPE_RX_DATA:
		case UART_EVT_TYPE_RX_DATA_TO:
		{
			uint16_t i;
			for(i=0; i<pev->len; i++) {
				uart_data.data[(uart_data.wr+i)&(UART_BUF_SIZE-1)] = pev->data[i];
			}
			uart_data.wr += pev->len;
			osal_start_timerEx(Hal_TaskID, USR_UART_RCV_DATA, 10);
		}
		break;
		
		case UART_EVT_TYPE_TX_COMPLETED:
			LOG("tx completed\r\n");
		break;
	}
}

/**
 * @fn      void HalPeripheral_Init(uint8 task_id)
 * @brief   Peripheral initialization
 * @param   task_id
 * @return  none
 */
void HalPeripheral_Init(uint8 task_id)
{
	Hal_TaskID = task_id;
	
	uart_Cfg_t cfg = {
		.tx_pin = P20,
		.rx_pin = P23,
		.baudrate = 115200,
		.use_fifo = TRUE,
		.hw_fwctrl = FALSE,
		.use_tx_buf = FALSE,
		.parity     = FALSE,
		.evt_handler = uart_receive_callback,
	};
	HalUartInit(UART1, cfg);//uart init
}

/**
 * @fn      uint16 HalPeripheral_ProcessEvent( uint8 task_id, uint16 events )
 * @brief   Peripheral event process
 * @param   task_id
 * @param	events
 * @return  none
 */
uint16 HalPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{
	if(task_id != Hal_TaskID)
    {
		return 0;
	}
	
	if( events & USR_UART_RCV_DATA )
    {
		LOG("uart rec:");
		while(uart_data.rd != uart_data.wr)
		{
			LOG("%x ", uart_data.data[(uart_data.rd)&(UART_BUF_SIZE-1)]);
			HalUartSendByte(UART1, uart_data.data[(uart_data.rd)&(UART_BUF_SIZE-1)]);
			uart_data.rd++;
		}
		LOG("\r\n");
        return ( events ^ USR_UART_RCV_DATA );
    }
	
    return 0;
}

/*********************************************************************
*********************************************************************/
